#!/usr/bin/Python
# -*- coding: utf-8 -*-
from os import path
import requests
import json
import re
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud, STOPWORDS
d = path.dirname(__file__)

#根据歌词id提取歌词
lrc_url = 'http://music.163.com/api/song/lyric?' + 'id=' + str(569213220) + '&lv=1&kv=1&tv=-1'
lyric = requests.get(lrc_url)
json_obj = lyric.text
j = json.loads(json_obj)
lrc = j['lrc']['lyric']
pat = re.compile(r'\[.*\]')
lrc = re.sub(pat, "", lrc)
lrc = lrc.strip()
print(lrc)
with open("F:\word_cloud\qq.txt","w") as f:#格式化字符串还能这么用！
        for i in lrc:
            f.write(i)

# Read the whole text.
file = open(path.join(d, 'qq.txt')).read()
##进行分词
#刚开始是分完词放进txt再打开却总是显示不出中文很奇怪
default_mode =jieba.cut(file)
text = " ".join(default_mode)
#text = text.encode('utf-8')
# read the mask image
# taken from
alice_mask = np.array(Image.open(path.join(d, "111.jpg")))
stopwords = set(STOPWORDS)
stopwords.add("said")
fontname = path.join(d, 'FZYBKSJW.TTF')
wc = WordCloud(
    #设置字体，不指定就会出现乱码,这个字体文件需要下载
    font_path = fontname,
    background_color="white",
    max_words=2000,
    mask=alice_mask,
    stopwords=stopwords)
# generate word cloud
wc.generate(text)

# store to file
wc.to_file(path.join(d, "qq_result.jpg"))

# show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()